<!-- 教育学习 -->
<template>
  <div class="eduction_index">
    <!-- 按钮 -->
    <div class="top">
      <div class="left">
        <el-button
          type="success"
          size="small"
          @click="addUpload"
          style="background: #26a661"
          icon="el-icon-plus"
          >新增</el-button
        >
      </div>
      <div class="right">
        <!-- 学习类型 -->
        <div class="xuexi">
          <p>学习类型：</p>
          <el-select
            v-model="listParams.learningType"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in educationTypeArr"
              :key="item.key"
              :label="item.value"
              :value="item.key"
            >
            </el-option>
          </el-select>
        </div>
        <!-- 标题 -->
        <div class="kejian">
          <p>标题：</p>
          <el-input
            v-model="listParams.title"
            placeholder="请输入……"
          ></el-input>
        </div>
        <el-button
          type="primary"
          size="small"
          @click="getEducationList"
          icon="el-icon-zoom-in"
          >搜索</el-button
        >
      </div>
    </div>

    <div style="padding: 10px" />

    <!-- 表格 -->
    <el-table
      v-loading="listLoading"
      :data="listArr"
      style="width: 100%"
      element-loading-text="Loading"
      border
      stripe
      fit
      highlight-current-row
    >
      <el-table-column label="序号" type="index" width="100px" align="center" />

      <el-table-column label="标题" align="center">
        <template slot-scope="scope">
          {{ scope.row.title ? scope.row.title : "--" }}
        </template>
      </el-table-column>

      <el-table-column label="封面" align="center">
        <template slot-scope="scope">
          <div v-for="(i, index) in scope.row.seriesCoverUrl" :key="index">
            <el-image
              style="width: 100px; height: 100px"
              :src="i"
              @click="seeImg(scope.row.seriesCoverUrl)"
              :preview-src-list="srcList"
            >
            </el-image>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="学习类型" align="center">
        <template slot-scope="scope">
          <p v-if="scope.row.learningType == 1">视频学习</p>
          <p v-else-if="scope.row.learningType == 2">文档资料</p>
          <p v-else-if="scope.row.learningType == 3">电子图书</p>
          <p v-else-if="scope.row.learningType == 4">专题学习</p>
          <!-- <p v-else-if="scope.row.learningType == 5">个人心得</p> -->
          <p v-else>--</p>
        </template>
      </el-table-column>

      <el-table-column label="是否为多个视频" align="center">
        <template slot-scope="scope">
          <p v-if="scope.row.learningType == 1">
            {{ scope.row.whetherVideos == 1 ? "是" : "否" }}
          </p>
          <p v-else>--</p>
        </template>
      </el-table-column>

      <el-table-column label="链接" align="center" width="200">
        <template slot-scope="scope">
          <div v-if="scope.row.learningType == 1">
            <div v-if="scope.row.url">
              <div v-for="(i, index) in scope.row.url" :key="index">
                <!-- <video width="175" height="100" controls>
                  <source :src="i" type="video/mp4" />
                </video> -->
                <a target="_blank" :href="i">视频链接{{ index + 1 }}</a>
              </div>
            </div>
            <div v-else>暂无数据</div>
          </div>
          <div v-else>--</div>
        </template>
      </el-table-column>

      <el-table-column label="文件名称" align="center" width="200">
        <template slot-scope="scope">
          <div v-if="scope.row.learningType == 1">---</div>
          <div v-else>
            <div v-if="scope.row.fileUrl">
              <div v-for="(i, index) in scope.row.fileUrl" :key="index">
                <p @click="prewFile(i.url)">{{ i.name }}</p>
                <!-- <a target="_blank" :href="i.url">{{ i.name }}</a> -->
              </div>
            </div>
            <div v-else>暂无数据</div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="上传人" align="center">
        <template slot-scope="scope">
          {{ scope.row.userName ? scope.row.userName : "--" }}
        </template>
      </el-table-column>

      <el-table-column label="上传时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.updateTime ? scope.row.updateTime : "--" }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="250px" align="center">
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="primary"
            plain
            @click="updateInfo(scope.row)"
            >编辑
          </el-button> -->
          <el-button
            size="mini"
            type="danger"
            plain
            @click="delInfo(scope.row.djStudyId)"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 对话框 -->
    <el-dialog
      :title="title"
      width="30%"
      :visible.sync="isShowAdd"
      top="5vh"
      :show-close="false"
      :destroy-on-close="true"
      @close="reset"
    >
      <el-form
        :model="dialogForm"
        ref="formRef"
        label-width="130px"
        :rules="formRules"
      >
        <el-form-item label="上传人" prop="year">
          <el-input v-model="dialogForm.userName" disabled></el-input>
        </el-form-item>

        <el-form-item label="标题" prop="title">
          <el-input
            v-model="dialogForm.title"
            placeholder="请输入……"
          ></el-input>
        </el-form-item>

        <el-form-item label="学习类型" prop="learningType">
          <el-select
            v-model="dialogForm.learningType"
            style="width: 100%"
            placeholder="请选择"
          >
            <el-option
              v-for="item in educationTypeArr"
              :key="item.key"
              :label="item.value"
              :value="item.key"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          v-if="dialogForm.learningType"
          label="封面"
          prop="seriesCoverUrl"
        >
          <el-upload
            style="width: 100%"
            :action="uploadUrl2"
            :on-success="handleSuccess"
            :headers="headers"
            :limit="1"
            :file-list="dialogForm.seriesCoverUrl"
            list-type="picture"
            :on-remove="onRemovePic"
            accept=".png,.jpg"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
          </el-upload>
        </el-form-item>

        <el-form-item v-if="dialogForm.learningType" label="文件">
          <!-- prop="fileUrl" -->
          <el-upload
            style="width: 100%"
            :action="uploadUrl2"
            :on-success="handleSuccessFile"
            :headers="headers"
            :file-list="dialogForm.fileUrl"
            :on-remove="onRemoveFile"
            :accept="fileAccept"
            :before-upload="beforeAvatarUpload"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" style="color: red">
              只能上传{{ fileAccept }}文件,且大小不能超过{{ fileSize }}M
            </div>
          </el-upload>
        </el-form-item>

        <el-form-item
          v-show="dialogForm.learningType == 1"
          label="是否为多个视频"
          prop="whetherVideos"
        >
          <el-radio v-model="dialogForm.whetherVideos" label="1">是</el-radio>
          <el-radio v-model="dialogForm.whetherVideos" label="2">否</el-radio>
        </el-form-item>

        <el-form-item v-show="dialogForm.learningType == 1" label="链接">
          <el-input
            v-if="dialogForm.whetherVideos == 2"
            v-model="dialogForm.url"
            placeholder="请输入……"
            @blur="videoUrlBlur"
          ></el-input>
          <div v-if="dialogForm.whetherVideos == 1">
            <div
              v-for="(item, index) in whetherVideosArr"
              :key="index"
              class="upload_url"
            >
              <el-input
                v-model="item.url"
                placeholder="请输入……"
                @blur="videoUrlBlur(index)"
              ></el-input>
              <i
                class="el-icon-circle-plus-outline"
                v-if="item.index == 0"
                @click="addUrl"
              ></i>
              <i
                class="el-icon-remove-outline"
                v-if="item.index"
                @click="delUrl(index)"
              ></i>
            </div>
          </div>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="reset">取 消</el-button>
        <el-button type="primary" @click="submitData(true, 'formRef')"
          >提 交</el-button
        >
      </div>
    </el-dialog>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listParams.pageNum"
      :limit.sync="listParams.pageSize"
      @pagination="getEducationList"
    />
  </div>
</template>

<script>
import moment from "moment";
import { uploadUrl2 } from "@/const";
import { getToken } from "@/utils/auth";
import { Base64 } from "js-base64";

import {
  apiEducationList, //列表
  apiEducationType, //学习类型
  apiUploadData, // 上传学习资料
  apiDeleteUploadInfo, // 删除
} from "@/api2/education";

export default {
  components: {},
  data() {
    return {
      uploadUrl2,
      headers: {
        Authorization: getToken(),
        platform: 'WEB'
      },
      // -----------------
      fileSize: 200, //上传文件大小
      fileAccept: "",
      srcList: [],
      whetherVideosArr: [], // 多个视频链接
      isShowAdd: false,
      educationTypeArr: [],
      kejianTypeArr: [],
      formRules: {
        title: [
          {
            required: true,
            message: "请输入标题",
            trigger: "change",
          },
        ],

        seriesCoverUrl: [
          {
            required: true,
            message: "请选择封面文件",
            trigger: "change",
          },
        ],
        fileUrl: [
          {
            required: true,
            message: "请选择文件",
            trigger: "change",
          },
        ],

        learningType: [
          { required: true, message: "请选择学习类型", trigger: "change" },
        ],

        url: [
          {
            required: true,
            message: "请输入链接地址",
            trigger: "blur",
          },
        ],
      },
      dialogForm: {
        whetherVideos: "",
        seriesCoverUrl: [],
        fileUrl: [],
      },
      ruzhiApplyDialog: false,
      title: "",
      total: 0,
      listLoading: false,
      listArr: [],
      listParams: {
        isDjCollect: null,
        learningType: null,
        title: null,
        pageNum: 1,
        pageSize: 10,
        userId: JSON.parse(sessionStorage.getItem("loginUserinfo")).uid,
      },
    };
  },
  watch: {
    "dialogForm.learningType"(val) {
      switch (val) {
        case 1: // 视频学习
          this.dialogForm.learningType == 1;
          this.whetherVideosArr = [
            {
              index: 0,
              url: null,
            },
          ]; // 多个视频链接
          this.dialogForm.whetherVideos = "2";
          this.fileAccept = ".mp4";
          break;
        case 2: // 文档资料
          this.fileAccept = ".docx,.doc";
          break;
        case 3: // 电子图书
          this.fileAccept = ".pdf,.txt";
          break;
        case 4: // 专题学习
          this.fileAccept = ".docx,.doc";
          break;
        case 5: // 学习心得
          this.fileAccept = ".zip,.rar";
          break;
        default: //默认数据
          this.fileAccept = "";
          break;
      }
    },
  },
  created() {
    this.init();
  },
  methods: {
    prewFile(file) {
      console.log(file);
      window.open(
        "http://192.168.1.40:8040/" +
          "onlinePreview?url=" +
          encodeURIComponent(Base64.encodeURI(file))
      );
      return;
      let lastIndex = file.lastIndexOf(".");
      let suffix = file.substring(lastIndex + 1);
      //文件格式是word文档、ppt、excel文件文件时
      if (
        suffix == "doc" ||
        suffix == "docx" ||
        suffix == "ppt" ||
        suffix == "xls" ||
        suffix == "pdf" ||
        suffix == "xlsx"
      ) {
        let fileUrl = encodeURIComponent(file);
        //使用Office Web查看器
        let officeUrl =
          "http://view.officeapps.live.com/op/view.aspx?src=" + fileUrl;
        window.open(officeUrl, "_target");
      } else {
        //其他文件格式比如pdf、图片、html
        window.open(file);
      }
    },

    // 获取格式化时间字符串
    getFormatedTimeStr(stamp, str = "MM-DD HH:mm") {
      return moment(stamp).format(str);
    },

    // 验证输入的地址是否为视频地址
    videoUrlBlur(index) {
      let reg = "/http.*\.(mp4|avi|flv)/gi";

      // 多条链接
      if (typeof index == "number") {
        if (!reg.match(this.whetherVideosArr[index].url)) {
          this.msgInfo("输入的视频地址不正确");
          this.whetherVideosArr[index].url = "";
        }
      } else {
        if (!reg.match(this.dialogForm.url)) {
          this.msgInfo("输入的视频地址不正确");
          this.dialogForm.url = "";
        }
      }
    },

    // 删除
    delInfo(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        apiDeleteUploadInfo(id)
          .then((res) => {
            if (res.code === 0) {
              this.msgSuccess("删除成功");
            } else {
              this.msgError("删除失败");
            }
            this.getEducationList();
          })
          .catch((err) => {
            console.log(err);
            this.msgError("删除失败");
            this.getEducationList();
          });
      });
    },

    // 编辑数据
    updateInfo(row) {
      this.isShowAdd = true;
      this.title = "编辑";
      this.dialogForm = row;
    },

    // 查看列表中的图片
    seeImg(imgSrc) {
      this.srcList = imgSrc;
    },

    // 添加链接
    addUrl() {
      let index = this.whetherVideosArr.length;
      this.whetherVideosArr.push({
        index,
        url: "",
      });
    },

    // 删除链接
    delUrl(index) {
      this.whetherVideosArr.splice(index, 1);
    },

    // 删除上传的图片
    onRemovePic(file, fileList) {
      this.dialogForm.seriesCoverUrl = [];
    },

    // 删除上传的文件
    onRemoveFile(file) {
      for (let i = 0; i < this.dialogForm.fileUrl.length; i++) {
        if (file.uid == this.dialogForm.fileUrl[i].uid) {
          this.dialogForm.fileUrl[i].splice(i, 1);
        }
      }
    },

    // 限制文件上传大小
    beforeAvatarUpload(file) {
      console.log(file.size / 1024 / 1024);
      let size = 200;
      const isLtM = file.size / 1024 / 1024 < size;
      console.log(isLtM);

      // if (this.fileAccept === ".mp4") {
      //   return;
      // } else {
      //   size = 50;
      // }

      if (!isLtM) {
        this.$message.error(`上传文件大小不能超过${size} MB!`);
      }
      return isLtM;
    },

    // 封面上传成功
    handleSuccess(res) {
      this.dialogForm.seriesCoverUrl = [];
      if (res.code === 0) {
        this.dialogForm.seriesCoverUrl.push({
          name: res.data.fileName,
          url: res.data.url,
        });

        this.$nextTick(() => {
          this.$refs.formRef.validateField("seriesCoverUrl"); // 手动触发fileList校验规则
        });
        this.$forceUpdate();
      } else {
        this.msgError("上传失败");
        this.dialogForm.seriesCoverUrl = [];
      }
    },

    // 文件上传成功
    handleSuccessFile(res) {
      if (res.code === 0) {
        this.dialogForm.fileUrl.push({
          name: res.data.fileName,
          url: res.data.url,
        });
        this.$refs.formRef.validateField("fileUrl"); // 手动触发fileList校验规则
      } else {
        this.msgError("上传失败");
        this.dialogForm.fileUrl = [];
      }
    },

    // 提交
    submitData(subtype, name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          // 封面
          let seriesCoverUrlArr = this.dialogForm.seriesCoverUrl.map((v) => {
            return v.url;
          });

          let data = {
            learningType: this.dialogForm.learningType,
            seriesCoverUrl: JSON.stringify(seriesCoverUrlArr),
            title: this.dialogForm.title,
            userId: this.dialogForm.userId,
            userName: this.dialogForm.userName,
            whetherVideos: this.dialogForm.whetherVideos,
          };

          let urlArr = [];
          if (
            this.dialogForm.whetherVideos == 1 &&
            this.dialogForm.whetherVideosArr[1].url
          ) {
            for (let i = 0; i < this.whetherVideosArr.length; i++) {
              urlArr.push(this.whetherVideosArr[i].url);
            }
          } else if (this.dialogForm.whetherVideos == 2) {
            if (this.dialogForm.url) {
              urlArr.push(this.dialogForm.url);
            }
          }

          // 文件
          if (this.dialogForm.fileUrl && this.dialogForm.fileUrl.length > 0) {
            let fileUrlArr = this.dialogForm.fileUrl.map((v) => {
              return {
                name: v.name,
                url: v.url,
              };
            });
            let fileUrlArr2 = this.dialogForm.fileUrl.map((v) => {
              return v.url;
            });

            data.fileUrl = JSON.stringify(fileUrlArr);
            urlArr = urlArr.concat(fileUrlArr2);
          }

          data.url = JSON.stringify(urlArr);

          apiUploadData(data)
            .then((res) => {
              if (res.code === 0) {
                this.msgSuccess("提交成功");
              } else {
                this.msgError("提交失败");
              }
              this.isShowAdd = false;
              this.getEducationList();
            })
            .catch((err) => {
              console.log(err);
              this.msgError("提交失败");
              this.getEducationList();
            });
          if (subtype) {
          } else {
          }
        }
      });
    },

    // 新增
    addUpload() {
      this.isShowAdd = true;
      this.title = "新增";

      this.dialogForm.userName = JSON.parse(
        sessionStorage.getItem("loginUserinfo")
      ).name;

      this.dialogForm.userId = JSON.parse(
        sessionStorage.getItem("loginUserinfo")
      ).uid;
    },

    reset() {
      this.isShowAdd = false;
      this.dialogForm = {};
      this.$nextTick(() => {
        this.$refs["formRef"].clearValidate();
      });
    },
    // 获取数据列表
    getEducationList() {
      this.listLoading = true;
      apiEducationList(this.listParams)
        .then((res) => {
          if (res.code === 0) {
            this.total = res.total;
            this.listArr = res.data;

            for (let i = 0; i < this.listArr.length; i++) {
              this.listArr[i].fileUrl = JSON.parse(this.listArr[i].fileUrl);
              this.listArr[i].seriesCoverUrl = JSON.parse(
                this.listArr[i].seriesCoverUrl
              );
              this.listArr[i].url = JSON.parse(this.listArr[i].url);
            }
          } else {
            this.total = 0;
            this.listArr = [];
          }
          this.listLoading = false;
        })
        .catch((err) => {
          console.log(err);
          this.total = 0;
          this.listArr = [];
          this.listLoading = false;
        });
    },
    // 学习类型
    getEducationType() {
      apiEducationType()
        .then((res) => {
          if (res.code === 0) {
            this.educationTypeArr = res.data;
            this.educationTypeArr.length = 4;
          } else {
            this.educationTypeArr = [];
          }
        })
        .catch((err) => {
          console.log(err);
          this.educationTypeArr = [];
        });
    },
    // 项目初始化
    init() {
      this.getEducationList();
      this.getEducationType();
    },
  },
};
</script>

<style lang="scss" scoped>
.eduction_index {
  padding: 15px;
  .top {
    height: 35px;
    display: flex;
    justify-content: space-between;
    .right {
      display: flex;
      .xuexi,
      .kejian {
        margin: 0 20px;
        display: flex;
        p {
          width: 30%;
        }
      }
    }
  }
  .upload_url {
    display: flex;
    align-items: center;
    margin: 4px 0;
    .el-icon-circle-plus-outline,
    .el-icon-remove-outline {
      cursor: pointer;
      margin-left: 10px;
      font-size: 20px;
    }
    .el-icon-circle-plus-outline:hover {
      color: #409eff;
    }
    .el-icon-remove-outline:hover {
      color: #f56c6c;
    }
  }
}
</style>
